import { randomString } from '@/utils'
import axios from 'axios'
import { getInfoFromOss } from '@/api/public'

export default {
  install(Vue, options) {
    Vue.prototype.uploadImgToOss = function(file, isPublic, isHttps) {
      return new Promise((resolve, reject) => {
        let imgUrl = ''
        getInfoFromOss(isPublic, isHttps).then(response => {
          // console.log('图片上传OSS信息：' + JSON.stringify(response))
          const info = response.data

          const randomStr = randomString(13)
          const param = new FormData()
          param.append('key', randomStr)
          param.append('policy', info.policy)
          param.append('OSSAccessKeyId', info.accessKeyId)
          param.append('success_action_status', 200)
          param.append('signature', info.signature)
          param.append('file', file.raw, file.name)
          param.append('chunk', '0')
          const config = {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Access-Control-Allow-Origin': '*'
            }
          }
          axios.post(info.host, param, config)
            .then(response => {
              // console.log('图片提交成功：' + JSON.stringify(response))
              if (response.status === 200) {
                this.$message({ message: '图片上传成功', type: 'success' })
              } else {
                this.$message({ message: '图片上传失败', type: 'error' })
              }
              imgUrl = info.host + '/' + randomStr
            })
            .then(() => {
              // console.log(response, '333333333')
              const data = response.data
              data.imgUrl = imgUrl
              data.fileKey = randomStr
              resolve(data)
            })
            .catch(error => {
              reject(error)
            })
        })
      })
    }
  }
}

